package com.team1.system.stats.controller;

import java.util.*;

import com.team1.system.librarycredit.domain.LibraryCredit;
import com.team1.system.librarycredit.service.ILibraryCreditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RestController
@RequestMapping("ats/credit")
public class StatsCreditController {

    @Autowired
    private ILibraryCreditService libraryCreditService;

//    统计每个用户的信用度
    @GetMapping("/user")
    public Map userCreditStats() {
        LibraryCredit libraryCredit= new LibraryCredit();
        List<LibraryCredit> list = libraryCreditService.selectLibraryCreditList(libraryCredit);
        Map<Long,Long> userCreditMap = new HashMap<>();
        for (LibraryCredit l : list) {
            long userId = l.getUserId();
            String creditOffset = l.getCreditOffset();
            if (userCreditMap.containsKey(userId)) {
                userCreditMap.put(userId, userCreditMap.get(userId) + Long.parseLong(creditOffset));
            } else {
                userCreditMap.put(userId, Long.parseLong(creditOffset));
            }
        }
        return userCreditMap;
    }
    //获取指定用户id的信用度
    public Long getCreditStatsById(Long uId){
        Map<Long,Long> userCreditMap = userCreditStats();
        Long userCredit = userCreditMap.get(uId);
        return userCredit;
    }

    //统计用户信用度前十用户id和信用度并排序
    public List<Map.Entry<Long,Long>> CreditStats(){
        Map<Long,Long> userCreditMap = userCreditStats();
        List<Map.Entry<Long,Long>> toptenCreditStats = userCreditMap.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .limit(10)
                .collect(Collectors.toList());
        // 返回结果
        return toptenCreditStats;
    }

}